import React, { useEffect, useState } from 'react';
import { Spin, Space, Button, Drawer, Modal, message } from 'antd';
import { useTablePipeline, features } from 'ali-react-table';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components';
import { UploadOutlined, FileTextOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';

import { PageLoading } from '@/components';
import { useExcel } from '@/hooks';
import { useTRState, TjTable } from '@/pages/ETrade/components';

import ImportBtn from './components/ImportBtn';
import MyDrawer from './components/MyDrawer';
import HistoryShot from './components/HistoryShot';
import DrawerContent from './components/DrawerContent';

import { default as HeadForm } from './form';
import {
  queryProvinceList,
  statementInfoList,
  delElectricityDetailList,
  addElectricityDetailList,
  editElectricityDetailList,
  getListContractTimeFrame,
  useNewServers,
} from './services';
import { tableColumns, getColumns, getTreeByCodes, fmtRes } from './helper';
import moment from 'moment';
import styles from './index.less';

const { confirm } = Modal;

const FreeSettlementDetails = (props) => {
  /** data */
  const exportKey = 'NewFreeSettlementDetails';
  const { menuCode, buttonPermissions } = props;
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    canImport: buttonPermissions.some((item) => item.menuCode === exportKey),

    // 初始化三件套
    spinning: true,
    error: '',
    power: [],
    // 表单
    formValues: {},
    selectedRowKeys: [],
    // 数据
    loading: true,
    tableData: [],
    stations: [],
  });
  const [visible, setVisible] = useState(false);
  const [editValues, setEditValues] = useState();
  const [btnLoading, setBtnLoading] = useState(false);
  const [refresh, setRefresh] = useState();
  const [contractTimeFrame, setContractTimeFrame] = useState([]);
  const [openKeys, setOpenKeys] = useState([]);

  useEffect(() => {
    init();
  }, []);

  /** apis */
  const init = async () => {
    // 权限
    const res = await queryProvinceList(menuCode);
    let power = [];
    let error = '';
    if (res?.statusCode === HttpCode.SUCCESS) {
      power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
    } else {
      error = res?.message || '系统异常';
    }
    setState({
      power,
      error,
      spinning: false,
    });
  };

  const getContractTimeFrame = (marketId) => {
    const currentMarketId = marketId ? marketId : state.formValues.marketId;
    if (currentMarketId === 'PXBSX') {
      // 陕西不用查
      return;
    }
    getListContractTimeFrame(currentMarketId).then((res) => {
      if (res && res.statusCode === '1000') {
        if (useNewServers.includes(currentMarketId)) {
          setContractTimeFrame(res.treeList);
        } else {
          setContractTimeFrame(res.data);
        }
      }
    });
  };

  /** methods */

  const getFormStationId = (record) => {
    let ids = [];
    const recursion = (arr, parentIds) => {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        if (item.children && item.children.length > 0) {
          recursion(item.children, [...parentIds, item.value]);
        }
        if (item.value === String(record.stationId)) {
          ids = [...parentIds, item.value];
          return;
        }
      }
    };
    recursion(state.power, []);
    return ids;
  };

  const add = () => {
    setVisible(true);
  };

  const del = (data) => {
    confirm({
      title: '确定删除此行数据吗？',
      onOk: () => {
        delElectricityDetailList({ id: data.id, marketId: state.formValues.marketId }).then(
          (res) => {
            if (res && res.statusCode && res.statusCode === '1000') {
              message.success('删除成功');
              setRefresh(moment().valueOf());
            } else {
              message.error('系统异常');
            }
          },
        );
      },
    });
  };

  const edit = (record) => {
    const newData = {
      ...record,
      statementMonth: record.statementMonth ? moment(record.statementMonth) : undefined,
      // adjustMonth: record.adjustMonth ? moment(record.adjustMonth) : undefined,
      stationId: getFormStationId(record),
    };
    setEditValues(newData);
    setVisible(true);
  };

  const submitData = (data) => {
    let fn = () => addElectricityDetailList(data, state.formValues.marketId);
    if (editValues) {
      fn = () => editElectricityDetailList(data, state.formValues.marketId);
    }
    setBtnLoading(true);
    fn()
      .then((res) => {
        if (res) {
          if (res.statusCode && res.statusCode === '1000') {
            message.success(editValues ? '修改成功' : '新增成功');
            setEditValues(undefined);
            setVisible(false);
            setRefresh(moment().valueOf());
          } else {
            let str = _.get(res, 'data', _.get(res, 'message', ''));
            if (str && _.isArray(str)) {
              str = res.data.join(',');
            }
            message.error(editValues ? `修改失败：${str}` : `新增失败：${str}`);
          }
        } else {
          message.error('系统异常');
        }
      })
      .finally(() => {
        setBtnLoading(false);
      });
  };

  const showHistory = async () => {
    const result = await MyDrawer.show({
      title: '操作日志',
      iconType: 1,
      width: 612,
      MyComponent: (props) => <HistoryShot formValues={state.formValues} {...props} />,
    });
    if (result?.index === 1) {
    }
    MyDrawer.dismiss();
  };

  const _onChangeForm = async (values) => {
    setState({ formValues: values, loading: true });
    const res = await statementInfoList(values);
    const tableData = fmtRes(res.data);
    setState({
      tableData,
      loading: false,
    });
    setOpenKeys([]);
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    let exportData = [state.tableData[0]]; // 合计
    state.tableData.slice(1).map(({ children, ...x }) => {
      exportData.push(x);
      exportData = exportData.concat(children);
    });
    useExcel({
      filename: `电费结算明细`,
      columns: tableColumns(state.formValues.marketId),
      data: exportData,
      merges: ['stationName'],
    });
  };

  // 关闭Drawer
  const onClose = () => {
    setVisible(false);
    setEditValues(undefined);
  };

  const pipeline = useTablePipeline()
    .input({
      columns: getColumns({ edit, del, marketId: state.formValues.marketId }),
      dataSource: state.tableData,
    })
    .primaryKey('tableId')
    // .use(features.rowGrouping({ defaultOpenAll: false }))
    .use(
      features.treeMode({
        openKeys: openKeys,
        defaultOpenKeys: false,
        onChangeOpenKeys(nextKeys) {
          setOpenKeys(nextKeys);
        },
      }),
    )
    .use(features.autoRowSpan())
    .appendRowPropsGetter((record, rowIndex) => {
      const hasBg = !!record.children || rowIndex === 0;
      const color = hasBg ? '#2D3133' : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  const _renderTable = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return <TjTable useVirtual="auto" {...pipeline.getProps()} />;
  };

  if (state.spinning) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!state.power?.length) return <TRDefault type="lock" />;
  const { formValues, canImport } = state;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.content}>
        <div className={styles.head}>
          <HeadForm
            power={state.power}
            onChange={_onChangeForm}
            refresh={refresh}
            getContractTimeFrame={getContractTimeFrame}
          />
          <Space size={16} wrap>
            <Button
              disabled={!state.tableData?.length}
              style={{ padding: 0 }}
              type="link"
              icon={<FileTextOutlined />}
              onClick={showHistory}
            >
              操作日志
            </Button>
            <ImportBtn
              disabled={!canImport}
              power={state.power}
              marketId={state.formValues.marketId}
            />
            <Button
              disabled={!state.tableData?.length}
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.main}>
          <div className={styles.box}>
            <div className={styles.flexcolumn}>
              <div className={styles.title}>
                电费结算明细
                <Button style={{ width: 98, height: 32 }} type="primary" onClick={add}>
                  新增
                </Button>
              </div>
              <div className={styles.table}>{_renderTable()}</div>
            </div>
          </div>
        </div>
        <Drawer
          title={editValues ? '编辑' : '新增'}
          placement="right"
          onClose={onClose}
          visible={visible}
          width="1164px"
          destroyOnClose
        >
          <DrawerContent
            marketId={formValues.marketId}
            submit={submitData}
            values={editValues}
            loading={btnLoading}
            optionsData={{
              marketingUnit: state.power,
              contractTimeFrame,
              marketId: formValues.marketId,
            }}
          />
        </Drawer>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(FreeSettlementDetails);
